package com.cloudfun.campusshare.util;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

/**
 * @Author : linyangping
 * @Date : Created in 8:21 PM 2019/11/16
 */
public class SendMailUtil {

    //邮件服务器主机名,邮箱的 SMTP 服务器地址
    private static String emailSMTPHost = "smtp.exmail.qq.com";
    //发件人邮箱
    private static String emailAccount = "filoink@hyperchain.cn";
    //发件人邮箱密码（授权码）
    private static String emailPassword = "87df62542331ce32";
    //发件人邮箱名
    private static String emailName = "飞洛印";

    public static boolean sendEmail(String toEmailAddress, String emailTitle, String emailContent) throws Exception {
        // 判断邮件地址是否存在
        if (!checkSend(toEmailAddress)) {
            return false;
        }
        Properties props = new Properties();
         // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 端口号
        props.put("mail.smtp.port", 465);
        // 设置邮件服务器主机名
        props.setProperty("mail.smtp.host", emailSMTPHost);
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");
        // SSL认证
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        // 设置是否使用ssl安全连接（一般都使用）
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);
        // 创建会话
        Session session = Session.getInstance(props);
        // 获取邮件对象
        // 发送的消息
        MimeMessage msg = new MimeMessage(session);
        //设置邮件标题
        msg.setSubject(emailTitle, "UTF-8");
        //设置邮件内容
        msg.setContent(emailContent, "text/html;charset=UTF-8");
        //设置显示的发件时间
        msg.setSentDate(new Date());
        //设置发件人邮箱: 发件人邮箱, 显示的昵称(只用于显示, 没有特别的要求), 昵称的字符集编码
        msg.setFrom(new InternetAddress(emailAccount,emailName, "UTF-8"));
        //设置收件人
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmailAddress));

        //得到邮差对象
        Transport transport = session.getTransport();
        //连接自己的邮箱账户
        transport.connect(emailSMTPHost, emailAccount, DesUtils.decryptToken(emailPassword));
        //发送邮件
        try {
            transport.sendMessage(msg, new Address[] { new InternetAddress(toEmailAddress) });
        } catch (Exception e){
            return false;
        }
        // 关闭
        transport.close();
        return true;
    }


    public static boolean checkSend(String toEmailAddress) throws GeneralSecurityException {
        Properties props = new Properties();
        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 端口号
        props.put("mail.smtp.port", 465);
        // 设置邮件服务器主机名
        props.setProperty("mail.smtp.host", emailSMTPHost);
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");
        // SSL认证
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        // 设置是否使用ssl安全连接（一般都使用）
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);
        // 创建会话
        Session session = Session.getInstance(props);
        session.setDebug(true);
        //2、通过session得到transport对象
        Transport transport;
        //3、使用邮箱的用户名和密码连上邮件服务器，发送邮件时，发件人需要提交邮箱的用户名和密码给smtp服务器，用户名和密码都通过验证之后才能够正常发送邮件给收件人。
        boolean result = false;
        try {
            transport = session.getTransport();
            transport.connect(emailSMTPHost, emailAccount, DesUtils.decryptToken(emailPassword));
            transport.close();
            result = true;
        } catch (NoSuchProviderException e1) {
            result = false;
        } catch (MessagingException e) {
            result = false;
        }

        return result;
    }
}

